#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>


#include "../common/sti/sti.h"
#include "net.h"
#include "db.h"




volatile _Atomic int g_shutdown = 0;


typedef struct {
	u32 id;
	
	char first_name[32];
	char last_name[32];
	
	bool sex;

	u64 age;
	u64 height;
	u16 weight;
	
} UserTest;


#define membersize(t, m) sizeof( ((t*)0)->m ) 


int main(int argc, char* argv[]) {
	string_internment_table_init(&global_string_internment_table);

	DB* db = calloc(1, sizeof(*db));
	DB_InitEmpty(db);
	db->backingDir = strint("./testdb");
	
	ObjStore* userStore = DB_LoadStore(db, "users");
	
	/*
	ObjDef* userDef = DB_AllocObjDef(db, "user");
	userDef->size = sizeof(UserTest);
	VEC_PUSH(&userDef->fields, ((FieldDef){
		.id = 0,
		.name = strint("id"),
		.offset = offsetof(UserTest, id),
		.len = membersize(UserTest, id),
		.type = 'i',
	}));
	VEC_PUSH(&userDef->fields, ((FieldDef){
		.id = 0,
		.name = strint("first_name"),
		.offset = offsetof(UserTest, first_name),
		.len = membersize(UserTest, first_name),
		.type = 'c',
	}));
	
	VEC_PUSH(&userDef->indices, ((IndexDef){
		.id = 0,
		.type = 'h',
		.name = strint("age"),
		.offset = offsetof(UserTest, age),
		.len = membersize(UserTest, age),
	}));
	
	DB_FinalizeObjDef(db, userDef);
	ObjStore* userStore = DB_CreateStore(db, userDef, "users");
	//*/
	UserTest u1 = {
		.id = 10032,
		.first_name = "steve",
		.last_name = "homeless",
		.sex = 0,
		.height = 172,
		.weight = 78,
		.age = 56,
	};

	ObjStore_Insert(db, userStore, &u1);
	u1.age = 23;
	ObjStore_Insert(db, userStore, &u1);
	
	UserTest resuser;
	int ret = ObjStore_IndexFetch(db, userStore, 0, &u1.age, &resuser);
	printf("fetch res: %d\n", ret);
	printf("user age: %ld\n", resuser.age);
	
	return 1;

	int epollfd = epoll_create(16);

	server_t* srv = server_init(epollfd, 42069);
//	srv->on_accept = accepted;
//	srv->user_data = cgi;
	
	printf("Starting server:\n");
	printf("  port: 42069\n");
	printf("\n");

	
	while(!g_shutdown) {
		
		server_tick(srv, 100);
//		sleep(1);
	}
	
	
	return 0;
}


/*
static void check_buffer(connection_t* con) {
	scgi_request* req = con->user_data;
	
	if(!req->buf) {
		req->buf = malloc(4096);
		req->buf_alloc = 4096;
		req->buf_remain = 4096;
		return;
	}
	
	req->buf_remain = req->buf_alloc;
	req->buf_alloc *= 2;
	req->buf = realloc(req->buf, req->buf_alloc);
}
*/


static void accepted(server_t* srv, connection_t* con) {
	
	printf("accepted connection\n");
	/*
	scgi_request* req = calloc(1, sizeof(*req));
	req->srv = srv->user_data;
	
	con->buffer_full = check_buffer;
	con->got_data = on_data;
	con->user_data = req;
	con->buf = &req->buf;
	con->buf_remain = &req->buf_remain;
	*/
}

static void on_data(connection_t* con) {
//	scgi_request* req = con->user_data;
//	scgi_server* cgi = con->srv->user_data;
	
}


